#-*- coding: utf-8 -*-

from ctypes import windll, c_ulong, sizeof, c_buffer, byref
import webbrowser
import time

psapi = windll.psapi
kernel = windll.kernel32

def EnumProcesses():
    arr = c_ulong * 256
    lpidProcess= arr()
    cb = sizeof(lpidProcess)
    cbNeeded = c_ulong()
    hModule = c_ulong()
    count = c_ulong()
    modname = c_buffer(30)
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_READ = 0x0010
    #Call Enumprocesses to get hold of process id's
    psapi.EnumProcesses(byref(lpidProcess),
                       cb,
                       byref(cbNeeded))
    #Number of processes returned
    nReturned = cbNeeded.value/sizeof(c_ulong())
    pidProcess = [i for i in lpidProcess][:nReturned]
    for pid in pidProcess:
        #Get handle to the process based on PID
        hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
        if hProcess:
            psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
            psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
            procname = "".join([ i for i in modname if i != '\x00'])

            #-- Clean up
            for i in range(modname._length_):
                modname[i]='\x00'
            kernel.CloseHandle(hProcess)
            if procname == 'SFCWebServer.exe':
                break
    else:
        webbrowser.open('SFCWebServer.exe')
        send_mail()

def send_mail():
    admins = ['zhujianhua@rosenbergerap.com']
    import smtplib
    from email.parser import Parser
    smtp = smtplib.SMTP('mailserver.rosenbergerap.com')

    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    
    detail = 'Time: %s\nSFCWebServer.exe auto restart by Python.\n'%now

    msg = Parser().parsestr('From: <shopfloors@sys_auto.com>\n'
        'To: <zhujianhua@rosenbergerap.com>\n'
        'Subject: SFCWebServer.exe Auto Restart By Python\n'
        '\n'
        '%s'%detail)
    smtp.sendmail(msg['From'], admins, msg.as_string())
    smtp.quit()
        
if __name__ == '__main__':
    while 1:
        EnumProcesses()
        time.sleep(5)
   